import { fetchPerson } from '../../../services/usercenter/fetchPerson';
import { phoneEncryption } from '../../../utils/util';
import { chooseAndUploadImage } from '../../../services/upload/imageUpload';
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    personInfo: {
      avatarUrl: '',
      nickName: '',
      gender: 0,
      phoneNumber: '',
    },
    showUnbindConfirm: false,
    isLoading: false, // 添加加载状态
    defaultAvatarUrl: 'https://tdesign.gtimg.com/miniprogram/template/retail/usercenter/icon-user-center-avatar@2x.png',
    pickerOptions: [
      {
        name: '男',
        code: '1',
      },
      {
        name: '女',
        code: '2',
      },
    ],
    typeVisible: false,
    genderMap: ['', '男', '女'],
  },
  onLoad() {
    this.init();
  },
  onShow() {
    // 每次显示页面时重新获取最新的用户信息，确保昵称等数据是最新的
    this.fetchData();
  },
  onPullDownRefresh() {
    // 下拉刷新时重新获取数据
    this.fetchData();
    wx.stopPullDownRefresh();
  },
  init() {
    this.fetchData();
  },
  fetchData() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      wx.switchTab({ url: '/pages/usercenter/index' });
      return;
    }

    // 显示加载状态
    this.setData({ isLoading: true });
    
    // 从后端获取用户信息，确保昵称等数据来自数据库
    wx.request({
      url: 'http://localhost:8080/api/wx/profile',
      method: 'GET',
      header: {
        'Authorization': token,
        'content-type': 'application/json'
      },
      success: (res) => {
        this.setData({ isLoading: false });
        if (res.statusCode === 200) {
          const personInfo = res.data;
          this.setData({
            personInfo: {
              ...personInfo,
              phoneNumber: phoneEncryption(personInfo.phoneNumber || ''),
              // 如果头像URL为空或无效，使用默认头像
              avatarUrl: personInfo.avatarUrl || this.data.defaultAvatarUrl
            }
          });
          console.log('个人资料页面用户信息更新成功:', {
            nickName: personInfo.nickName,
            avatarUrl: personInfo.avatarUrl || this.data.defaultAvatarUrl
          });
        } else {
          this.showErrorAndRetry(res.data.message || '获取用户信息失败');
        }
      },
      fail: (err) => {
        this.setData({ 
          isLoading: false,
          // 网络失败时使用默认头像
          'personInfo.avatarUrl': this.data.defaultAvatarUrl
        });
        console.error('获取用户信息失败:', err);
        this.showErrorAndRetry('网络请求失败，请检查网络连接');
      }
    });
  },
  onClickCell({ currentTarget }) {
    const { dataset } = currentTarget;
    const { nickName, phoneNumber } = this.data.personInfo;

    switch (dataset.type) {
      case 'gender':
        this.setData({
          typeVisible: true,
        });
        break;
      case 'name':
        wx.navigateTo({
          url: `/pages/user/name-edit/index?name=${encodeURIComponent(nickName || '')}`,
        });
        break;
      case 'avatarUrl':
        this.toModifyAvatar();
        break;
      case 'phoneNumber':
        wx.navigateTo({
          url: `/pages/user/phone-edit/index?phone=${encodeURIComponent(phoneNumber || '')}`,
        });
        break;
      default: {
        break;
      }
    }
  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onConfirm(e) {
    const { value } = e.detail;
    this.updateProfile({ gender: parseInt(value) });
    this.setData({
      typeVisible: false,
      'personInfo.gender': parseInt(value),
    });
  },

  // 更新用户信息到后端
  updateProfile(updates) {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: 'http://localhost:8080/api/wx/profile',
      method: 'PUT',
      header: {
        'Authorization': token,
        'content-type': 'application/json'
      },
      data: updates,
      success: (res) => {
        if (res.statusCode === 200) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '更新成功',
            theme: 'success',
          });
          // 更新本地用户信息
          if (res.data.userInfo) {
            wx.setStorageSync('userInfo', res.data.userInfo);
          }
        } else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: res.data.message || '更新失败',
            theme: 'error',
          });
        }
      },
      fail: (err) => {
        console.error('更新用户信息失败:', err);
        Toast({
          context: this,
          selector: '#t-toast',
          message: '网络请求失败',
          theme: 'error',
        });
      }
    });
  },
  async toModifyAvatar() {
    try {
      // 使用通用的图片选择和上传服务
      const uploadResult = await chooseAndUploadImage({
        uploadType: 'avatar',
        maxSize: 10 * 1024 * 1024 // 10MB
      });
      
      if (uploadResult.cancelled) {
        // 用户取消选择，不显示错误
        return;
      }
      
      if (uploadResult.success) {
        // 更新本地显示
        this.setData({
          'personInfo.avatarUrl': uploadResult.url
        });
        
        // 更新到后端数据库
        this.updateProfile({ avatarUrl: uploadResult.url });
        
        Toast({
          context: this,
          selector: '#t-toast',
          message: '头像更新成功',
          theme: 'success',
        });
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: uploadResult.message || '头像上传失败',
          theme: 'error',
        });
      }
    } catch (error) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.message || '修改头像出错了',
        theme: 'error',
      });
    }
  },
  
  // t-avatar 组件内置错误处理，不需要额外的错误处理函数

  // 显示错误信息并提供重试选项
  showErrorAndRetry(message) {
    wx.showModal({
      title: '获取用户信息失败',
      content: message + '\n\n是否重试？',
      confirmText: '重试',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.fetchData(); // 重新获取数据
        }
      }
    });
  },
  
  logout() {
    try {
      wx.removeStorageSync('token');
      wx.removeStorageSync('userInfo');
    } catch (e) {
      // ignore
    }
    Toast({
      context: this,
      selector: '#t-toast',
      message: '已退出登录',
      theme: 'success',
      duration: 800,
    });
    setTimeout(() => {
      wx.switchTab({ url: '/pages/usercenter/index' });
    }, 500);
  },
});
